package com.dongge.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by Administrator on 2015/10/18.
 */

public abstract class CURDDaoBase1<T> {

    private SessionFactory sessionFactory;
    private Class<T> clazz = null;

    public CURDDaoBase1() {

        try {
            ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
            clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    @Resource
//    public SessionFactory getSessionFactory() {
//        return sessionFactory;
//    }
//
//    public void setSessionFactory(SessionFactory sessionFactory) {
//        this.sessionFactory = sessionFactory;
//    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * 增
     *
     * @param model
     */
    public void save(T model) {
        if (model != null) {
            getSession().save(model);
        }
    }

    /**
     * 改
     *
     * @param model
     */
    public void update(T model) {
        if (model != null) {
            getSession().update(model);
        }
    }

    /**
     * 查一个
     *
     * @param id
     */
    public T get(Long id) {
        if (id != null) {
            return (T) getSession().get(clazz, id);
        }
        return null;
    }

    /**
     * 查询所有
     *
     * @return
     */
    public List<T> getAll() {
        String hsql = "from " + clazz.getSimpleName();
        return getSession().createQuery(hsql).list();
    }

    /**
     * 删
     *
     * @param id
     */
    public void delete(Long id) {
        T model = get(id);
        if (model != null) {
            getSession().delete(model);
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}